﻿// For an introduction to the Navigation template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232506
(function () {
    "use strict";

    WinJS.Binding.optimizeBindingReferences = true;

    var app = WinJS.Application;
    var activation = Windows.ApplicationModel.Activation;
    var nav = WinJS.Navigation;
    var isSearchActivated = false;
    var isSettingsInitialized = false;

    app.addEventListener("activated", function (args) {
        if (args.detail.kind === activation.ActivationKind.launch) {
            if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
                
                Data.resetCache();
                try {
                    registerBackgroundTask();
                    TileUpdate.updateTile();
                } catch (e) {
                    console.log(e);
                }

            } else {
                // TODO: This application has been reactivated from suspension.
                // Restore application state here.
            }

            if (app.sessionState.history) {
                nav.history = app.sessionState.history;
            }
            initSettings();

            args.setPromise(WinJS.UI.processAll().then(function () {
                if (args.detail.arguments !== "") {

                    var catItem = null;
                    try {
                        catItem = JSON.parse(args.detail.arguments);
                    } catch (e) {

                    }
                    return WinJS.Navigation.navigate('/pages/groupDetail/groupDetail.html', {
                        from: 'categoryItem',
                        item: catItem
                    });

                } else {
                    if (nav.location) {
                        nav.history.current.initialPlaceholder = true;
                        return nav.navigate(nav.location, nav.state);
                    } else {
                        return nav.navigate(Application.navigator.home);
                    }
                }

            }));


        } else if (args.detail.kind === activation.ActivationKind.search) {

            isSearchActivated = true;
            initSettings();

            args.setPromise(WinJS.UI.processAll().then(function () {
                if (!nav.location) {
                    nav.history.current = { location: Application.navigator.home, initialState: {} };
                }
                nav.navigate("/pages/search/searchResults.html", { queryText: args.detail.queryText });

            }));
        }
    });

    app.oncheckpoint = function (args) {
        // TODO: This application is about to be suspended. Save any state
        // that needs to persist across suspensions here. If you need to 
        // complete an asynchronous operation before your application is 
        // suspended, call args.setPromise().
        app.sessionState.history = nav.history;
    };

    app.start();

    // Register a Background Task for Periodic Tile Updates
    function registerBackgroundTask() {

        // Promote app as lock screen app to allow TimeTrigger
        Windows.ApplicationModel.Background.BackgroundExecutionManager.requestAccessAsync();

        var builder = new Windows.ApplicationModel.Background.BackgroundTaskBuilder();
        builder.name = "SampleTileUpdateBackgroundTask";
        builder.taskEntryPoint = "js\\tileUpdateBackgroundTask.js";

        builder.setTrigger(new Windows.ApplicationModel.Background.TimeTrigger(15, false));
        //builder.setTrigger(new Windows.ApplicationModel.Background.SystemTrigger(Windows.ApplicationModel.Background.SystemTriggerType.timeZoneChange, false)); // Test Trigger for debugging only

        builder.addCondition(new Windows.ApplicationModel.Background.SystemCondition(Windows.ApplicationModel.Background.SystemConditionType.internetAvailable));

        var task = builder.register();

        console.log('Background task "' + builder.name + '" registered.');
    }

    function unregisterBackgroundTask() {
        var iter = Windows.ApplicationModel.Background.BackgroundTaskRegistration.allTasks.first();
        var hascur = iter.hasCurrent;
        while (hascur) {
            var cur = iter.current.value;
            if (cur.name === "SampleTileUpdateBackgroundTask") {
                cur.unregister(true);
            }
            hascur = iter.moveNext();
        }
    }

    function onSettingsCommand(settingsCommand) {
        // The URI to launch
        var datenSchutzURL = WinJS.Resources.getString('privacyPolicy').value;

        var settingsSiteNoteTitle = WinJS.Resources.getString('SettingsSiteNoteTitle').value;
        if (settingsCommand.id === settingsSiteNoteTitle) {
            datenSchutzURL = WinJS.Resources.getString('siteNote').value;
        }

        var uriToLaunch = datenSchutzURL;
        // Create a Uri object from a URI string 
        var uri = new Windows.Foundation.Uri(uriToLaunch);

        Windows.System.Launcher.launchUriAsync(uri).then(
           function (success) {
               if (success) {
                   // URI launched
               } else {
                   // URI launch failed
               }
           });
    }

    function onCommandsRequested(eventArgs) {

        if (eventArgs.request.applicationCommands.size > 2) {
            return;
        }
        
        var privacyPolicyTitle = WinJS.Resources.getString('privacyPolicyTitle').value;
        var settingsSiteNoteTitle = WinJS.Resources.getString('SettingsSiteNoteTitle').value;

        var settingsCommandSiteNote = new Windows.UI.ApplicationSettings.SettingsCommand(settingsSiteNoteTitle, settingsSiteNoteTitle, onSettingsCommand);
        var settingsCommand = new Windows.UI.ApplicationSettings.SettingsCommand(privacyPolicyTitle, privacyPolicyTitle, onSettingsCommand);
        eventArgs.request.applicationCommands.append(settingsCommandSiteNote);
        eventArgs.request.applicationCommands.append(settingsCommand);
    }
    function initSettings() {

        if (!isSettingsInitialized) {
            isSettingsInitialized = true;

            WinJS.Application.onsettings = function (e) {

                //get settings titles from resource file
                var settingsOptionsTitle = WinJS.Resources.getString('SettingsOptionsTitle').value;

                e.detail.applicationcommands = {
                    "optionDiv": { href: "/settings/optionsFlyout/optionsFlyout.html", title: settingsOptionsTitle }
                    //"impressumSettingDiv": { href: "/settings/impressum/impressum.html", title: settingsSiteNoteTitle }
                };

                WinJS.UI.SettingsFlyout.populateSettings(e);
            }

            var settingsPane = Windows.UI.ApplicationSettings.SettingsPane.getForCurrentView();
            settingsPane.addEventListener("commandsrequested", onCommandsRequested);
        }
    }

})();
